/*******************************************************************************
 * (c) Copyright 2017 lvxi. All Rights Reserved.
 ******************************************************************************/

package edu.jxufe.nb112.blog.web.controller.upload;

import com.alibaba.fastjson.JSONObject;
import edu.jxufe.nb112.blog.core.persist.service.user.FileResourceService;
import edu.jxufe.nb112.blog.web.controller.BaseController;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.util.Map;

/**
 * Created by lvxi on 2017/2/7.
 */
@Controller
@RequestMapping("/file")
public class FileResourceController extends BaseController {
    private final static Logger LOG = LoggerFactory.getLogger(FileResourceController.class.getName());


    @Autowired
    private FileResourceService fileResourceService;

    /**
     * 文件上传进度
     * @param progressId
     * @param response
     * @return
     */
    @RequestMapping(value = "/progress", method = RequestMethod.POST)
    public @ResponseBody
    Object shwoFileProgress(@RequestParam("progressId")String progressId, HttpServletResponse response) {
        JSONObject jsonObject = new JSONObject();
        Map<String, String> progressMap = (Map<String, String>) getSession().getAttribute("progressMap");
        if(progressMap != null) {
           String progressValue =  progressMap.get(progressId);
            if("100".equals(progressValue))  {
                progressMap.remove(progressValue);
                if(progressMap.isEmpty()) {
                    getSession().removeAttribute("progressMap");
                }
            }
            jsonObject.put("progress",progressValue);
        }
        return jsonObject;

    }

/*
private FileLog saveFile( String type , MultipartFile multipartFile){
    //HttpServletRequest request = getRequest();
    String path = null;
    long startTime =  System.currentTimeMillis();
    if(StringUtils.isBlank(staticDir)){
        logger.error("静态资源static.dir目录未配置");
        throw new RuntimeException("静态资源static.dir目录未配置");
    }

    String dir = staticDir;
    String relationDir = getFileDirByUpLoadType(type);

    if(StringUtils.isBlank(relationDir)){
        logger.error("文件上传目录未配置");

        return null;
        //throw new RuntimeException("文件上传目录未配置");
    }
    path = relationDir.replaceAll("\\|\\\\|//","/");

    if(path.startsWith("/")) path = path.substring(1);

    Calendar date= Calendar.getInstance();
    SimpleDateFormat yearFormat=new SimpleDateFormat( "yyyy");
    SimpleDateFormat monthFormat=new SimpleDateFormat( "MM");
    SimpleDateFormat dayFormat=new SimpleDateFormat( "dd");
    SimpleDateFormat fileNameFormat=new SimpleDateFormat( "HHmmssSSSS");

    String year=yearFormat.format(date.getTime());
    String month=monthFormat.format(date.getTime());
    String day=dayFormat.format(date.getTime());
    String fileName=fileNameFormat.format(date.getTime())+getFileSuffix(multipartFile.getOriginalFilename());
    String dateDir = "/"+year+"/"+month+"/"+day+"/";

    dir = dir.replaceAll("\\|\\\\|//","/");

    if (!dir.endsWith("/")) dir+="/";
    dir +=path;
    if(!hasDir(dir)){
        logger.error("文件上传目录不存在");
        throw new RuntimeException("文件上传目录不存在");
    }
    path+=dateDir;
    dir+=dateDir;
    if(!hasDir(dir)){
        File dirFile = new File(dir);
        if(!dirFile.mkdirs()){
            logger.error("文件上传日期子目录生成失败");
            throw new RuntimeException("文件上传日期子目录生成失败");
        }
    }
    path = path+ fileName;
    dir+=fileName;
    File fileTo = new File(dir);
    try {
        multipartFile.transferTo(fileTo);
    } catch (IOException e) {
        e.printStackTrace();
        logger.error("文件上传失败");
        return null;
    }

    int  spentTime = new Long(System.currentTimeMillis()-startTime).intValue();

    //存储文件上传记录
    FileLog fileLog = new FileLog();
    fileLog.setName(multipartFile.getOriginalFilename());
    fileLog.setCreator(getCurrentUserId());
    fileLog.setType(type);
    fileLog.setSize(multipartFile.getSize());
    fileLog.setPath(path);
    fileLog.setSpentTime(spentTime);
    fileService.addFileLog(fileLog);
    return fileLog;
}
*/
/*
private boolean deleteFile(Long id ){
    FileLog fileLog = fileService.get(id);
    if (fileLog !=null){
        File file = new File(staticDir  +"/"+ fileLog.getPath());
        if(file.isFile() && file.delete()) {
            fileService.deleteFileLog(fileLog);
            return true;
        }
    }
    return false;
}
    @RequestMapping(value = "/upload", method = RequestMethod.POST)
    public @ResponseBody
    Object uploadFileSubmit(@RequestParam("type")String type, HttpServletRequest request) {
        CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver(getSession().getServletContext());
        JSONObject msgObj = new JSONObject();
        if(multipartResolver.isMultipart(request)){
            MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest)request;
            Iterator<String> iter = multiRequest.getFileNames();
            JSONArray fileStatusArray = new JSONArray();
            boolean isUploadAllOk = true;
            while(iter.hasNext()){
                List<MultipartFile> files = multiRequest.getFiles(iter.next()); //可能一个输入框传多个文件
                Iterator<MultipartFile> subIt = files.iterator();
                while (subIt.hasNext()){
                    JSONObject fileStatus = new JSONObject();
                    MultipartFile file = subIt.next();
                    fileStatus.put("name",file.getName());
                    boolean isUploadOk = false;
                    if(file!=null ) {
                        FileLog fileLog = saveFile(type,file);
                        if(fileLog!=null){
                            isUploadOk = true;
                            String fileId = DESUtils.encodeTimestap(fileLog.getId()+"",desLiveTime,desPassword);
                            fileStatus.put("url",fileLog.getPath());
                            fileStatus.put("fileId",fileId);
                        }else {
                            isUploadAllOk = false;
                        }

                    }else {
                        isUploadAllOk = false;
                    }
                    fileStatus.put("success",isUploadOk);
                    fileStatusArray.add(fileStatus);
                }

            }
            if(!isUploadAllOk) {
                msgObj.put("error","文件上传失败！");
            }
            msgObj.put("result",fileStatusArray);
        }
        return msgObj;
    }



    @RequestMapping(value = "/ueditor/upload", method = RequestMethod.POST)
    public @ResponseBody
    Object ueditorUploadFileSubmit(@RequestParam("opt")String type, HttpServletRequest request) {
        CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver(getSession().getServletContext());
        JSONObject fileStatus = new JSONObject();
        if(multipartResolver.isMultipart(request)){
            MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest)request;
            Iterator<String> iter = multiRequest.getFileNames();
            while(iter.hasNext()) {  //只有一个文件
                MultipartFile file = multiRequest.getFile(iter.next()); //可能一个输入框传多个文
                if (file != null) {
                    FileLog fileLog = saveFile(type, file);
                    if (fileLog != null) {
                        fileStatus.put("url", fileLog.getPath());
                        fileStatus.put("state","SUCCESS");
                        fileStatus.put("title", file.getOriginalFilename());
                        fileStatus.put("original", file.getOriginalFilename());
                        return fileStatus;
                    } else {

                    }
                }

            }
            fileStatus.put("state","FAILURE");
        }
        return fileStatus;
    }


    @RequestMapping(value = "/delete", method = RequestMethod.GET)
    public @ResponseBody
    Object uploadFileSubmit(@RequestParam("fileId") String fileId) {
        fileId = DESUtils.decodeTimestap(fileId,desPassword);
        if (StringUtils.isNotBlank(fileId) && StringUtils.isNumeric(fileId)){
            if(deleteFile(Long.parseLong(fileId))){
                return MessageUtils.success();
            }

        }
        return MessageUtils.failure();
    }
*/

        /**
         * 目录是否存在
         * @param dir
         * @return
         */
    public boolean hasDir(String dir){
        File file = new File(dir);
        if(file.isDirectory() && file.exists()) {
            return true;
        }
        return false;
    }

    /**
     * 获取文件后缀,包含.
     * @return
     */
    public String getFileSuffix(String fileName){
        int index = fileName.lastIndexOf('.');
        if(index>=0){
            return '.'+fileName.substring(index+1);
        }
        return "";
    }

}
